package com.itheima.web;

import com.itheima.pojo.Item;
import com.itheima.pojo.ShoppingCart;
import com.itheima.pojo.User;
import com.itheima.service.ItemService;
import com.itheima.service.PurchaseHistoryService;
import com.itheima.service.ShoppingCartService;
import com.itheima.util.SessionMailUtils;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/orderServlet2")
public class OrderServlet2 extends HttpServlet {
    private ShoppingCartService service = new ShoppingCartService();
    private ItemService itemService = new ItemService();
    private PurchaseHistoryService purchaseHistoryService = new PurchaseHistoryService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 通过session获取user对象
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        Integer userId = user.getId();

        List<ShoppingCart> shoppingCartGoods = service.selectByBuyerId(userId);

        for (ShoppingCart shoppingCartGood : shoppingCartGoods) {
            Item item = itemService.selectById(shoppingCartGood.getItemId());
            itemService.updateSalesVolume(item.getSalesVolume() + 1, item.getId());

            purchaseHistoryService.add(item.getId(), userId, item.getSellerId());
        }

        response.sendRedirect("purchase-succeeded.jsp");

        // 发送邮件
        try {
            // 1.创建Session
            Session mailSession = SessionMailUtils.createSession();

            // 2.创建邮件对象（Message抽象类的子类对象）
            MimeMessage msg = new MimeMessage(mailSession); // 传入session
            msg.setFrom(new InternetAddress("******")); // 发件人

            String userEmail = user.getEmail();
            String userName = user.getUsername();
            String text = "亲爱的" + userName + "，您购买的商品已经发货。";

            msg.setRecipient(Message.RecipientType.TO, new InternetAddress(userEmail)); // 收件人
            msg.setSubject("发货通知", "utf-8"); // 标题
            msg.setText(text, "utf-8", "html"); // 正文

            // 3.发送邮件
            Transport.send(msg);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
